package com.angel.kuaidi.activity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.angel.kuaidi.R;
import com.angel.kuaidi.db.DB;
import com.angel.kuaidi.entity.HistoryInfo;
import com.angel.kuaidi.entity.WuliuCompanyInfo;
import com.angel.kuaidi.utils.SharePreferenceManager;
import com.angel.kuaidi.utils.StringUtils;
import com.angel.kuaidi.utils.Utils;
import com.angel.kuaidi.utils.UtilsLog;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

public class HistoryActivity extends BaseActivity {

	public final String[] STATE = { "在途中", "已发货", "疑难件", "已签收", "已退货" };

	private ListView lv_list;
	private TextView tv_nodata;

	private HistoryListAdapter adapter;
	private ArrayList<HistoryInfo> list;

	private int currentPage = 1;
	private int pageSize = 25;
	private long count = 0;
	private int deleteCount = 0;

	private View moreView;
	ProgressBar pb_bar;
	TextView tv_content;

	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {

			//
			if (adapter != null) {
				adapter.notifyDataSetChanged();
			}
			if (list.size() == count && lv_list.getFooterViewsCount() > 0) {
				lv_list.removeFooterView(moreView);
			}
			if (count == 0) {
				lv_list.setVisibility(View.GONE);
				tv_nodata.setVisibility(View.VISIBLE);
			}

			super.handleMessage(msg);
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//
		setView(R.layout.history_list);
		setTitle("返回", "历史列表");

		initData();
		initView();
		registerListener();
		display();
		adView();
	}

	private void adView() {

		View v = findViewById(R.id.adview);
		SharedPreferences share = mContext.getSharedPreferences("adview_flag", Context.MODE_PRIVATE);
		if (share.getBoolean("flag", false)) {
			v.setVisibility(View.VISIBLE);
		} else {
			v.setVisibility(View.GONE);
		}
	}

	private void initData() {

		count = DB.getInstance(mContext).getCount(HistoryInfo.class);
		list = new ArrayList<HistoryInfo>();
		adapter = new HistoryListAdapter(mContext, list);
	}

	private void initView() {

		lv_list = (ListView) findViewById(R.id.lv_list);
		tv_nodata = (TextView) findViewById(R.id.tv_nodata);

		moreView = LayoutInflater.from(mContext).inflate(R.layout.more_click, null);
		pb_bar = (ProgressBar) moreView.findViewById(R.id.pb_bar);
		tv_content = (TextView) moreView.findViewById(R.id.tv_content);

	}

	private void registerListener() {

		lv_list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View v, int arg2, long arg3) {
				//
				if (v.equals(moreView)) {
					tv_content.setText("正在加载...");
					pb_bar.setVisibility(View.VISIBLE);
					new RequestDataAsy().execute();
					return;
				}
				final HistoryInfo hi = list.get(arg2);
				final WuliuCompanyInfo w = new WuliuCompanyInfo();
				w.chinesename = hi.chinesename;
				w.pinyinname = hi.pinyinname;

				Intent intent = new Intent(mContext, KuaidiDetailActivity.class);
				intent.putExtra("postid", hi.postid);
				intent.putExtra("company", w);
				intent.putExtra("from", 1);
				startActivity(intent);
			}
		});

		lv_list.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

				final HistoryInfo h = list.get(arg2);

				new AlertDialog.Builder(mContext).setTitle("删除快递单").setPositiveButton("确定", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {

						//
						DB.getInstance(mContext).delete(HistoryInfo.class, "_id=" + h._id);
						list.remove(h);
						count--;
						deleteCount++;
						handler.obtainMessage().sendToTarget();
						Utils.toast(mContext, "删除成功!");
						dialog.dismiss();
					}
				}).setNegativeButton("点错了", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				}).setMessage("是否删除单号：" + StringUtils.setText(h.postid, "未知")).create().show();

				return true;
			}
		});
	}

	private void display() {

		if (count > 0) {
			new RequestDataAsy().execute();
		} else {
			lv_list.setVisibility(View.GONE);
			tv_nodata.setVisibility(View.VISIBLE);
		}
	}

	class RequestDataAsy extends AsyncTask<Void, Void, List<HistoryInfo>> {

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}

		@Override
		protected void onPostExecute(List<HistoryInfo> result) {

			tv_content.setText("点击加载");
			pb_bar.setVisibility(View.GONE);
			if (result != null) {
				list.addAll(result);
				if (currentPage == 1) {
					if (list.size() < count) {
						lv_list.addFooterView(moreView);
					}
					lv_list.setAdapter(adapter);
					lv_list.setVisibility(View.VISIBLE);
					tv_nodata.setVisibility(View.GONE);
				}

				if (list.size() == count && lv_list.getFooterViewsCount() > 0) {
					lv_list.removeFooterView(moreView);
				}
				currentPage++;
				adapter.notifyDataSetChanged();
			} else {

				if (currentPage == 1) {
					lv_list.setVisibility(View.GONE);
					tv_nodata.setVisibility(View.VISIBLE);
				}

			}
			super.onPostExecute(result);
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected List<HistoryInfo> doInBackground(Void... arg0) {

			try {
				return DB.getInstance(mContext).queryAll(HistoryInfo.class, "1=1 limit " + (pageSize * (currentPage - 1) - deleteCount) + " , " + pageSize);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}
	}

	class HistoryListAdapter extends BaseAdapter {

		private LayoutInflater inflater;
		private ArrayList<HistoryInfo> list;

		public HistoryListAdapter(Context context, ArrayList<HistoryInfo> list) {

			this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			this.list = list;
		}

		@Override
		public int getCount() {

			return this.list.size();
		}

		@Override
		public Object getItem(int position) {

			return null;
		}

		@Override
		public long getItemId(int position) {

			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			View view = inflater.inflate(R.layout.history_list_item, null);
			TextView tv_order = (TextView) view.findViewById(R.id.tv_order);
			TextView tv_company = (TextView) view.findViewById(R.id.tv_company);
			TextView tv_time = (TextView) view.findViewById(R.id.tv_time);

			final HistoryInfo hi = this.list.get(position);
			tv_order.setText(hi.postid + "(" + getStatusType(hi.status) + ")");
			tv_company.setText(hi.chinesename);
			tv_time.setText(getDate(hi.time));

			return view;
		}

		private String getStatusType(String status) {

			int index = Integer.parseInt(status);
			if (index < 0 || index >= STATE.length) {
				return "异常";
			}
			return STATE[index];
		}

		public String getDate(String date) {

			UtilsLog.i("msg", "time:" + date);
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			long time = Long.parseLong(date);
			Date d = new Date(time);
			try {
				return formatter.format(d);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return "";
		}

	}
}
